
function PBPAcleanupScript () {
    var jsonScript = document.getElementById('po_pbpa_google_script');
    if (jsonScript) {
        jsonScript.parentNode.removeChild(jsonScript);
    }
}

function PBPAshowPopulation () {
    var h = document.getElementsByTagName ("h1")[0];
    if (h.textContent != "Statistics - Pardus Cluster") return;
    
    var ths = document.getElementsByTagName ("th");
    var th = null;
    for (var i=0; i<ths.length; i++) {
        if (ths[i].textContent == "Federation Contingent") {
            th = ths[i];
            th.parentNode.parentNode.parentNode.id = "pbpa_fed_table";
            break;
        }
    }
    if (!th) return;
    th.innerHTML += " [<span id='pbpa_last_check_ticks'>"+PBPAgetTicksSinceLastCheck()+"</span> ticks since last check - <a style='color:navy;' href='javascript:PBPAresetTracker();void(0);'>reset</a>] <a style='color:navy' href='javascript:PBPAshowDetails();void(0);' id='pbpa_details_link'>(details>>>)</a>"
    PBPAcheckChanges ();
}

function PBPAresetTracker () {
    localStorage.removeItem ("po_pbpa_population_old");
    localStorage.removeItem ("po_pbpa_population");
    window.location = "statistics.php?display=parduscluster";
}

function PBPAcloseEmpTable () {
    var ths = document.getElementsByTagName ("th");
    var tbl = null;
    for (var i=0; i<ths.length; i++) {
        if (ths[i].textContent == "Empire Contingent") {
            tbl = ths[i].parentNode.parentNode.parentNode;
            break;
        }
    }
    if (!tbl) return;
    tbl.parentNode.style.display = "none";
}

function PBPAfindRow (tbl, name) {
    for (var i=2; i<tbl.rows.length; i++) {
        if (tbl.rows[i].cells[2].textContent == name) return tbl.rows[i];
    }
    return null;
}

function PBPAgetRings (population) {
    if (population < 5000) return 1;
    else if (population < 15000) return 2;
    else if (population < 30000) return 3;
    return 4;
}

function PBPAshowBaseInfo (data) {
    var tbl = document.getElementById ("pbpa_fed_table");
    if (!tbl) return;
    
    for (var i=2; i<tbl.rows.length; i++) {
        var row = tbl.rows[i];
        row.appendChild (document.createElement("td"));
        row.appendChild (document.createElement("td"));
        row.appendChild (document.createElement("td"));
        row.appendChild (document.createElement("td"));
        row.appendChild (document.createElement("td"));
    }
    
    var entries = data.feed.entry;
    for (var i=0; i<entries.length; i++) {
        var entry = entries[i];
        var tr = null;
        if (entry.gs$cell.col == '2' && entry.gs$cell.row != '1') {
            tr = PBPAfindRow (tbl, entry.content.$t);
            if (!tr) {
                continue;
            }
            tr.cells[5].textContent = entries[i+14].content.$t; // Target population
            tr.cells[6].textContent = PBPAgetRings (Number(tr.cells[3].textContent.replace(",", ""))); // Current rings
            tr.cells[7].textContent = entries[i+6].content.$t; // Planned rings
            tr.cells[8].textContent = entries[i-1].content.$t; // Location
            tr.cells[9].textContent = entries[i+15].content.$t; // Owner
            tr.cells[5].align = "right";
            tr.cells[6].align = "center";
            tr.cells[7].align = "center";
            
            if (Number(tr.cells[5].textContent.replace("k","000")) > Number(tr.cells[3].textContent.replace(",", ""))) {
                tr.cells[5].style.color = "red";
                tr.cells[5].setAttribute ("title", "Current population is bellow the planned level !!!");
            } else {
                tr.cells[5].style.color = "lime";
                tr.cells[5].setAttribute ("title", "Current population is on or above the planned level.");
                tr.cells[3].style.color = "lime";
                tr.cells[4].style.color = "lime";
            }
            if (Number(tr.cells[7].textContent) > Number(tr.cells[6].textContent)) {
                tr.cells[6].style.color = "red";
                tr.cells[7].style.color = "red";
                tr.cells[6].setAttribute ("title", "Current amount of rings is bellow the plan !!!");
                tr.cells[7].setAttribute ("title", "Current amount of rings is bellow the plan !!!");
            } else {
                tr.cells[6].style.color = "lime";
                tr.cells[7].style.color = "lime";
                tr.cells[6].setAttribute ("title", "Current amount of rings is on or above the plan.");
                tr.cells[7].setAttribute ("title", "Current amount of rings is on or above the plan.");
            }
        }
    }
    PBPArefreshPinDetails ();
}

function PBPArefreshPinDetails () {
    var lnk = document.getElementById ('pbpa_details_link');
    var pinned = localStorage.getItem ("pbpa_pin_details");
    if (pinned == "true") {
        lnk.textContent = " (keep compact view)";
        lnk.setAttribute ("href", "javascript:PBPApinDetails(false);void(0);");
    } else {
        lnk.textContent = " (keep details view)";
        lnk.setAttribute ("href", "javascript:PBPApinDetails(true);void(0);");
    }
}

function PBPApinDetails (pin) {
    localStorage.setItem ("pbpa_pin_details", String (pin));
    PBPArefreshPinDetails ();
}

function PBPAgetTicksSinceLastCheck () {
    var clock = top.POGetClock ();
    var last = localStorage.getItem ("pbpa_last_check");

    if (last) {
        var lastd = new Date();
        lastd.setTime (last);
    } else {
        var lastd = new Date ();
        lastd.setTime (clock.pardus_time.getTime() - (3*3600000));
    }
    var ticks = clock.getSBTicksSince (lastd);
    return ticks;
}

function PBPAsaveLastCheck () {
    var clock = top.POGetClock ();
    var pc = clock.pardus_time;

    localStorage.setItem ("pbpa_last_check", pc.getTime());
}

function PBPArefreshBaseInfo () {
    var key = localStorage.getItem ("po_pbpa_definition_url");
    PBPAcleanupScript ();
    
    // Create the script node
    // Look here for details: http://stackoverflow.com/questions/2924563/access-google-apps-public-spreadsheet-via-javascript
    var script = document.createElement('script');
    script.setAttribute('src', 'https://spreadsheets.google.com/feeds/cells'
                         + '/' + key 
                         + '/2/public/values' + '?alt=json-in-script&callback=PBPAshowBaseInfo');
    script.setAttribute('id', 'po_pbpa_google_script');
    script.setAttribute('type', 'text/javascript');
    document.documentElement.firstChild.appendChild(script);
}

function PBPAshowDetails () {
    var tbl = document.getElementById ("pbpa_fed_table");
    if (!tbl) return;

    PBPAcloseEmpTable ();

    // Add the header row
    var head = document.createElement ("tr");
    head.innerHTML = "<th>No.</th><th>F</th><th>Name</th><th>Curr. pop.</th><th>Trend</th><th>Plan. pop.</th><th>Curr. rings</th><th>Plan. rings</th><th>Location</th><th>Owner</th>";
    tbl.firstChild.insertBefore (head, tbl.rows[1]);
    tbl.rows[0].cells[0].setAttribute ("colspan", "10");
    tbl.parentNode.setAttribute ("width", "66%");
    
    // Refresh base info
    var lnk = document.getElementById ('pbpa_details_link');
    lnk.textContent = "(refreshing...)";
    PBPArefreshBaseInfo ();
}

function PBPAcheckChanges () {
    var tbl = document.getElementById ("pbpa_fed_table");
    if (!tbl) return;
    
    tbl.rows[0].cells[0].setAttribute("colspan", "5");
    
    var set = localStorage.getItem ("po_pbpa_population");
    if (!set) set = "";
    var ticks = PBPAgetTicksSinceLastCheck();
    var storeTicks = ticks;
    if (ticks == 0) {
        var newset = localStorage.getItem ("po_pbpa_population_old");
        if (set == "") storeTicks = 0;
        else storeTicks = Number(set.split("&")[0].split("#")[1]);
        if (newset) set = newset;
    }
    document.getElementById ('pbpa_last_check_ticks').textContent = storeTicks;
    // The format is: "Base 1 name#50,048&Base 2 name#30,234&"
    
    var newset = "Ticks#"+ticks+"&";
    for (var i=1; i<tbl.rows.length; i++) {
        var row = tbl.rows[i];
        var name = row.cells[2].textContent;
        var pop = row.cells[3];
        var size = Number(pop.textContent.replace(",", ""));
        
        var trendCell = document.createElement ("td");
        row.appendChild (trendCell);
        
        if (set.indexOf (name) == -1) {
            newset += name+"#"+size+"&";
            continue;
        }
        
        var split = set.split (name+"#");
        split = split[1].split ("&");
        var oldpop = Number(split[0].replace(",", ""));
        
        var color = null;
        var title = "";
        var rate = Math.round (Math.abs (oldpop-size) / oldpop * 1000);
        var rpt = Math.round(rate / storeTicks)/10;
        rate = rate / 10;
        var trend = null;
        if (size > oldpop) {
            style = "color:lime;";
            title = "Population has increased since last visit by "+rate+"% ("+rpt+"% per tick.";
            trend = "&uarr;&uarr;";
        } else if (size == oldpop) {
            style = "color:yellow;";
            title = "Population is the same as last time.";
            trend = "&rarr;";
        } else {
            if (size > 50000) {
                style = "color:lime;";
                title = "Population has dropped since last visit by "+rate+"% ("+rpt+"% per tick.";
            } else {
                if (rpt > 4) {
                    style = "color:red;font-weight:bold;";
                } else {
                    style = "color:orangered;";
                }
                title = "Population has dropped since last visit by "+rate+"% ("+rpt+"% per tick.";
            }
            trend = "&darr;&darr;";
        }
        
        if (trend) {
            trendCell.innerHTML = trend;
            trendCell.setAttribute ("title", title);
            trendCell.setAttribute ("align", "center");
            if (style) trendCell.setAttribute ("style", style);
        }
        newset += name + "#" + size + "&";
        if (style) pop.setAttribute ("style", style);
        pop.setAttribute ("title", title);
        //pop.innerHTML += trend;
    }
    if (ticks > 0 || set == "") {
        localStorage.setItem ("po_pbpa_population_old", set);
        localStorage.setItem ("po_pbpa_population", newset);
        PBPAsaveLastCheck ();
    }
    var pinned = localStorage.getItem ("pbpa_pin_details");
    if (pinned == "true") {
        PBPAshowDetails ();
    }
}

function PBPAhideTop () {
    var h1 = document.getElementsByTagName ("h1")[0];
    var div = h1.parentNode;
    var td = div.parentNode;
    
    td.insertBefore (h1, div);
    div.style.display = "none";
    div.id = "pbpa_cluster_info";
    h1.setAttribute ("align", "center");
    
    var cont = document.createElement ("div");
    cont.innerHTML = "<a style='color:lime;' href='javascript:document.getElementById(\"pbpa_cluster_info\").style.display=\"block\";void(0);'>(show cluster and subsidy info)</a><br><br>";
    cont.setAttribute ("align", "center");
    td.insertBefore (cont, div);
}

if (document.getElementsByTagName ("h1")[0].textContent == "Statistics - Pardus Cluster") {
    PBPAhideTop ();
    PBPAshowPopulation ();
}